<?php
class CMS_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        // set up acl
        $acl = new Zend_Acl ( );
      
        // add the roles
        $acl->addRole ( new Zend_Acl_Role ( 'guest' ) );
        $acl->addRole ( new Zend_Acl_Role ( 'member' ), 'guest' );
        $acl->addRole ( new Zend_Acl_Role ( 'admin' ), 'guest' );
        
        // add the resources
        $acl->addResource ( new Zend_Acl_Resource ( 'site' ) );
        $acl->addResource ( new Zend_Acl_Resource ( 'menu' ) );
        $acl->addResource ( new Zend_Acl_Resource ( 'error' ) );        
        $acl->addResource ( new Zend_Acl_Resource ( 'member' ) );
		$acl->addResource ( new Zend_Acl_Resource ( 'admin' ) );
      
        // set up the access rules
        $acl->allow ( null, array ('site', 'error', 'menu' ) );
         
        // a guest can only read content and login
        //$acl->allow ( 'guest', 'search', array ('index', 'search' ) );
        $acl->allow ( 'guest', 'site' );
        $acl->allow ( 'guest', 'menu' );
        $acl->allow ( 'member', 'member' );
   
        // administrators can do anything
        $acl->allow ( 'admin', null );
        
        $auth = Zend_Auth::getInstance ();
        if ($auth->hasIdentity ()) {
            $identity = $auth->getIdentity ();
            $role = strtolower ( $identity->role );
        } else { 
            $role = 'guest';
        }
        	
        // fetch the current user
        $controller = $request->controller;
        $action = $request->action;
        
        if (! $acl->isAllowed ( $role, $controller, $action )) {
            if ($role != 'admin' && $controller == 'admin') {
                $request->setControllerName ( 'admin' );
                $request->setActionName ( 'login' );
            } else if ($role == 'guest' && $controller == 'member') {
            	$request->setControllerName ( 'site' );
                $request->setActionName ( 'login' );
            } else {
                $request->setControllerName ( 'error' );
                $request->setActionName ( 'noauth' );
            }
        }
    }
}